#!/usr/bin/env python
# coding=utf-8
# @FileName :hashlib_util.py
# @Time     :2022/2/10 14:43
# @Author   :ZXC
# @Desc     :哈希加密md5
import hashlib

__all__ = ['md5_encryption']

from loguru import logger


def md5_encryption(raw_str, sha_str='', to_upper=False, is_16: bool = False):
    """
    执行md5加密
    Args:
        raw_str: 原始字符串
        sha_str: md5加密的盐值。用于提高破解者的撞库成本
        to_upper: 是否将加密后的结果转大写
        is_16: 加密后的位数，默认32位，否则为16位

    Returns: 经md5加密后的字符串

    """
    logger.debug(f'执行方法：md5_encryption({raw_str}, {sha_str}, {to_upper})')
    md5_obj = hashlib.md5(sha_str.encode('utf-8'))
    md5_obj.update(str(raw_str).encode('utf-8'))
    encrypted_str = md5_obj.hexdigest().upper() if to_upper else md5_obj.hexdigest()
    if is_16:
        encrypted_str = encrypted_str[8:-8]
    logger.debug(f'加密完成：md5_encryption({raw_str}, {sha_str}, {encrypted_str})')
    return encrypted_str


if __name__ == '__main__':
    print(md5_encryption('zxc', 'zxc'))
    print(md5_encryption('zxc', 'zxc', to_upper=True, is_16=False))
